package com.study.test;

import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.study.config.MainConfigOfProfile;
import org.springframework.context.ApplicationContext;




/**
 * @author wuwenbo
 * @date 2020/4/6 - 22:08
 */

public class IOCTest_Profile {
   //1.使用命令行动态参数: 在虚拟机参数位置加载 -Dspring.profiles.active=dev
    //2.用代码的方式激活某种环境
    @Test
    public void test_Profile() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);
        printBeans(applicationContext);
        System.out.println("=========");
        String[] names =  applicationContext.getBeanNamesForType(DataSource.class);
       for(String name : names){
           System.out.println(name);
       }
    }

    @Test
    public void test_Profile2() {
        //1.创建一个 applicationContext
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //**我们这里不能写有参构造器，有参构造器创建 ioc 容器会直接注册配置类并刷新，我们就没有机会 激活运行环境了，所以这里用无参
        //2.设置需要激活的环境
        applicationContext.getEnvironment().setActiveProfiles("test","dev");
        //3.注册主配置类
        applicationContext.register(MainConfigOfProfile.class);
        //4.启动刷新容器
        applicationContext.refresh();
        printBeans(applicationContext);
        System.out.println("==========");
        String[] names =  applicationContext.getBeanNamesForType(DataSource.class);
        for(String name : names){
            System.out.println(name);
        }
    }
    private void printBeans(ApplicationContext applicationContext) {
        for (String name : applicationContext.getBeanDefinitionNames()) {
            System.out.println(name);
        }
    }
}
